package com.atguigu.tingshu.common.login;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.awt.*;

@Component
@Aspect
public class TsLoginAspect {
    @Autowired
    private RedisTemplate redisTemplate;

    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(tsLogin)")
    public Object doConcurrentOperation(ProceedingJoinPoint joinPoint, TsLogin tsLogin) throws Throwable {
        //切面类中将用户id存储到本地线程
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes serletRequestAttributes = (ServletRequestAttributes) requestAttributes;

        // 获取请求对象
        HttpServletRequest request = serletRequestAttributes.getRequest();
        //获取响应对象
        // HttpServletResponse response = serletRequestAttributes.getResponse();
        String token = request.getHeader("token");
        //判断注解属性
        if (tsLogin.required()) {
            //必须登录
            if (StringUtils.isEmpty(token)){
                //未登录
                throw  new GuiguException(ResultCodeEnum.LOGIN_AUTH);

            }else {
                //去缓存中获取用户id
                String loginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
                UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(loginKey);
                if (null == userInfo){
                    //未登录
                    throw  new GuiguException(ResultCodeEnum.LOGIN_AUTH);
                }
            }
        }
        try {
            //判断token是否为空
            if (!StringUtils.isEmpty(token)){
                String loginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
                UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(loginKey);
                //不为空,将用户id存入本地线程
             if (null != userInfo){
                 AuthContextHolder.setUserId(userInfo.getId());
             }
             }
            return joinPoint.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        } finally {
            //清除本地线程
            AuthContextHolder.removeUserId();
        }
    }
}
